#include <stdio.h>
#include "strindex.h"
#define MAXLINE 1000
#define MAXPATTERN 20
#define LIGHTGREEN "\e[1;32m"
#define NONE "\e[0m" 

int strindex(char source[], char searchfor[]);
void printcolor(char line[], int pos, char pattern[], int row_number);

int main(int argc, char* argv[])
{
    char line[MAXLINE];
    int found = 0, pos, row_number = 0;
    FILE* fp = fopen(argv[2], "r");
    char pattern[MAXPATTERN];
    strcpy(pattern, argv[1]);
    
    while((fgets(line, MAXLINE, fp)) != NULL) {
        row_number++;
        if((pos = strrindex(line, pattern)) >= 0) {
            printcolor(line, pos, pattern, row_number);
            // printf("Position of the pattern in the line is %d\n\n", pos);
            found++;
        }
    }
    if (found > 1)
        printf("\nStatistical Result: %d appearances in the file\n", found);
    else if (found == 1)
        printf("\nStatistical Result: %d appearance in the file\n", found);
    else
        printf("\nStatistical Result: no appearance in the file\n");

    return found;
}

int strindex(char s[], char t[])
{
    int i, j, k;
    //i is the length of fitted string

    for(i = 0; s[i] != '\0'; i++) {
        for(j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++)
            ;
        if(k > 0 && t[k] == '\0')
            return i;
    }

    return -1;
}

void printcolor(char line[], int pos, char pattern[], int row_number)
{
    int new_str1_len = pos + 1,
        new_str2_len = strlen(line) - pos - strlen(pattern) + 1;
    char new_str1[new_str1_len],
         new_str2[new_str2_len];
    
    strncpy(new_str1, line, pos);
    new_str1[pos] = '\0';
    int i;
    for(i = 0; i < new_str2_len; i++)
        new_str2[i] = line[pos + strlen(pattern) + i];

    printf(">> Line %d:\n   %s", row_number, new_str1);
    printf(LIGHTGREEN "%s" NONE, pattern);
    printf("%s", new_str2);
}    
